<script lang="ts" setup>
import { ref, watch, computed, reactive, onMounted } from "vue";
import { formatTimestamp, formatBigNumber, scientificToDecimal } from "@/comm/format";
import JEmpty from "@/components/j-empty/index.vue";
import YHR from "./YHR.vue";
import { YTab as YTabscript } from "./scripts/YTab";
import JNumber from "@/components/j-number/index.vue";
import XNumber from "@/components/x-number/index.vue";
import JLoding from "@/components/j-loding/index.vue";
import { useTokens } from "@/stores/tokens";
import { useRouter } from "vue-router";
import { useCapital } from "@/stores/capital";
import i18n from "@/locals";
import cloneDeep from 'lodash/cloneDeep';
import { getTodayYesterdayPrice } from "@/comm/web3";
import { useKline } from "@/stores/kline";
import XDecimals from "@/components/x-decimals/index.vue";
import JSort from "@/components/j-sort/index.vue";
import { Sort, SortEnum, SortType } from "@/comm/sort";
const tokens = useTokens();
const capital = useCapital();
const kline = useKline();
const showEmpty = computed(() => {
    return capital.positions.length == 0 || listArr.value.length == 0;
});
const listArr = ref<any>([]);
watch(() => capital.positions, () => {
    if (capital.positions.length > 0) {
        updateBalance()
    }
})
const updateBalance = async () => {
    let todayList = capital.positions; //今日持仓数据
    for await (const item of todayList) {
        let stableList = [
            '0xdac17f958d2ee523a2206206994597c13d831ec7', // USDT
            '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', // USDC
            '0x83f20f44975d03b1b09e64809b757c47f942beea', // sDAI
            '0x6b175474e89094c44da98b954eedeac495271d0f', // DAI
            '0x6c3ea9036406852006290770bedfcaba0e23a0e8',//PYUSD
        ];
        if (stableList.includes(item.contractAddress)) {
            item.lastPrice = 1;
        } else if (item.symbol.endsWith('ETH')) {
            item.lastPrice = await (kline.map.find(i => i.tokenAddress === '0x'))?.lastPrice || null; // 币对价格 查找该币对在 map 中对应的币对价格
        } else if (item.symbol.endsWith('BTC')) {
            item.lastPrice = await (kline.map.find(i => i.baseCurrency === 'BTC'))?.lastPrice || null; // 币对价格 查找该币对在 map 中对应的币对价格
        } else {
            let symbolInfo = await (kline.map.find(i => i.tokenAddress === item.contractAddress))
            if (!symbolInfo?.symbol) {
                symbolInfo = await (kline.map.find(i => i.baseCurrency === item.symbol))
            }
            let lastPrice;
            if (symbolInfo?.symbol.startsWith('1000')) {
                lastPrice = symbolInfo.lastPrice / 1000
            } else {
                lastPrice = symbolInfo?.lastPrice
            }
            item.lastPrice = lastPrice || null;
        }
        item.yesterdayBlance = await getYesterdayBlance(item); // 昨日持仓数量
        item.value = item.lastPrice !== 0 ? item.balance * item.lastPrice : null; // 总价值 = 持仓数量 * 最新价格
        item.balanceChange = item.balance - item.yesterdayBlance; // 持仓数量变化 = 今日持仓数量 - 昨日持仓数量
        item.change = getChangeUsd(item.contractAddress, item, item.lastPrice); // 涨跌幅
        // console.log(`
        //     币对:${item.symbol}
        //     价值:${item.lastPrice},
        //     今日持仓数量:${item.balance},
        //     昨日持仓数量:${item.yesterdayBlance},
        // `)
    }
    todayList.sort((a, b) => b.value - a.value)
    console.log('持仓数据', todayList)
    listArr.value = todayList || [];
    // listArr.value = []
};
//计算今天昨天持仓涨跌幅  (今日持仓数量 - 昨日持仓数量) * 币对最新价格
const getChangeUsd = (address: any, today: any, price: any) => {
    let yesterdayList = capital.prevPositions; //昨日持仓
    let yesterdaySymbol = yesterdayList.find(i => i.contractAddress == address); //昨日持仓中该币对的信息
    if (yesterdaySymbol) {
        let diff = today.balance - yesterdaySymbol.balance; //差额 =  今日持仓数量 - 昨日持仓数量 
        let change = diff * price
        return scientificToDecimal(change)
    }
    return today?.usd
};
//返回对应币对昨日持仓数量
const getYesterdayBlance = (item: any) => {
    let yesterdayList = capital.prevPositions; //昨日持仓
    let yesterdayBlance = yesterdayList.find(i => i.contractAddress == item.contractAddress)?.balance || 0;
    return yesterdayBlance || 0.00
}

onMounted(async () => {
    await capital.loadCapitals();
});

let loading = false;

const onDetail = (coin: any) => {
    // router.push({ name: 'token', params: { id: coin.contractAddress } });
    window.open("/token/" + coin.contractAddress);
};

const sorts = ref<SortType[]>([
    { key: i18n.global.t("message.YTabCol_.tableB.a"), val: SortEnum.NONE },
    { key: i18n.global.t("message.YTabCol_.tableB.c"), val: SortEnum.NONE },
    { key: i18n.global.t("message.YTabCol_.tableB.d"), val: SortEnum.NONE },
    { key: i18n.global.t("message.YTabCol_.tableB.b"), val: SortEnum.NONE }
]);
const sort = new Sort(sorts);
sort.callFun = function (item: SortType) {
    const key = item.key;
    switch (item.val) {
        case SortEnum.NONE:
            sortTableList(key, SortEnum.NONE);
            break;
        case SortEnum.UP:
            sortTableList(key, SortEnum.UP);
            break;
        case SortEnum.DOWN:
            sortTableList(key, SortEnum.DOWN);
            break;
    }
    console.log('yzt回调', item);
}
const sortTableList = (key: any, type: number) => {
    let newList = cloneDeep(listArr.value)
    const defaultSort = (list: any) => {
        return list.sort((a: any, b: any) => b.value - a.value)
    }
    if (type == 0) {
        newList = defaultSort(newList)
        listArr.value = newList
        return
    }
    // 持仓币对
    if (key == i18n.global.t("message.YTabCol_.tableB.a")) {
        if (type == 1) {
            newList = newList.sort((a: any, b: any) => a.symbol.charAt(0).toLowerCase().localeCompare(b.symbol.charAt(0).toLowerCase()));
        }
        if (type == 2) {
            newList = newList.sort((a: any, b: any) => b.symbol.charAt(0).toLowerCase().localeCompare(a.symbol.charAt(0).toLowerCase()));
        }
    }
    //价格
    if (key == i18n.global.t("message.YTabCol_.tableB.c")) {
        newList = newList.sort((a: any, b: any) => type == 1 ? b.lastPrice - a.lastPrice : a.lastPrice - b.lastPrice)
    }
    //持仓
    if (key == i18n.global.t("message.YTabCol_.tableB.d")) {
        newList = newList.sort((a: any, b: any) => type == 1 ? b.balance - a.balance : a.balance - b.balance)
    }
    //价值
    if (key == i18n.global.t("message.YTabCol_.tableB.b")) {
        newList = newList.sort((a: any, b: any) => type == 1 ? b.value - a.value : a.value - b.value)
    }
    listArr.value = newList
}
</script>

<template>
    <div class="ytabCol">
        <div class="ytabCol-box">
            <div class="tab-h">{{ $t("message.YTabCol_.b") }}</div>
            <YHR></YHR>
            <VContainer class="table-box">
                <VRow class="row-first c-title-5">
                    <VCol class="col_title col_1 col-first align-center">{{ $t("message.YTabCol_.tableB.a") }}
                        <JSort :sort="sorts[0]" :call-fun="sort.onDown.bind(sort)"></JSort>
                    </VCol>
                    <VCol class="col_title col_2 d-flex align-center">{{ $t("message.YTabCol_.tableB.c") }}
                        <JSort :sort="sorts[1]" :call-fun="sort.onDown.bind(sort)"></JSort>
                    </VCol>
                    <VCol class="col_title col_3 money align-center">
                        <span class="c-left"> {{ $t("message.YTabCol_.tableB.d") }}
                        </span>
                        <JSort :sort="sorts[2]" :call-fun="sort.onDown.bind(sort)"></JSort>
                        <span class="c-right"></span>
                    </VCol>
                    <VCol class="col_title col_4 col-gap">
                        <span class="c-left">{{ $t("message.YTabCol_.tableB.b") }}</span>
                        <JSort :sort="sorts[3]" :call-fun="sort.onDown.bind(sort)"></JSort>
                        <span class="c-right"></span>
                    </VCol>
                </VRow>
                <div class="j-loding" v-if="capital.positionLoading">
                    <JLoding></JLoding>
                </div>
                <div class="j-auto" v-else>
                    <VRow v-for="(item, i) in listArr">
                        <VCol class="col_1 sps-col col-first">
                            <img :src="tokens.getImg(item.symbol)" class="mr-2 coin-t" />
                            <span class="long-text coin-link" @click="onDetail(item)">{{ item.symbol }}</span>
                        </VCol>
                        <VCol class="col_2 sps-col  j-number">
                            <JNumber :num="item.lastPrice" prefix="$" price v-if="item.lastPrice > 0.001"></JNumber>
                            <XDecimals :num="item.lastPrice" prefix="$" titleClass="title-4-bold"
                                subTitleClass="num-zero-bold" v-else></XDecimals>
                        </VCol>
                        <VCol class="col_3 c-title-4 money align-center">
                            <!-- 今日持仓 -->
                            <div class="c-left">
                                <XNumber :num="item.balance" :type="0">
                                </XNumber>
                            </div>
                            <!-- 昨日变化率 -->
                            <div class="c-right">
                                <XNumber :num="item.balanceChange" zeroAccord="+" :showEmpty="true" :isZeroColor="true"
                                    :isColor="true" :isAdd="true">
                                </XNumber>
                            </div>
                        </VCol>
                        <VCol class="col_4 sps-col col-gap">
                            <!-- 持仓价值 -->
                            <div class="c-left">
                                <XNumber :num="item.value" prefix='$' :showEmpty="true"></XNumber>
                            </div>
                            <!-- 持仓涨幅 -->
                            <div class="c-right">
                                <XNumber :num="item.change" zeroAccord="+" :showEmpty="true" :isZeroColor="true"
                                    :isColor="true" prefix='$' :isAdd="true">
                                </XNumber>
                            </div>
                        </VCol>
                    </VRow>
                    <JEmpty v-show="showEmpty"></JEmpty>
                </div>
            </VContainer>
        </div>
    </div>
</template>

<style lang="less" scoped>
.j-number {}

:deep(.num-txt) {
    // color: var(--color-2) !important;
    // font-weight: 700;
    font-size: 14px;
}


.ytabCol {
    height: 100%;
    background-color: var(--card);

    .ytabCol-box {
        height: 100%;
    }

    .tab-h {
        // padding: 12px 20px 11px 20px;
        padding: 0 var(--space) 0 var(--space);
        display: flex;
        align-items: center;
        height: 40px;
        font-size: 16px;
        font-weight: bold;
    }

    .table-box {

        height: calc(100% - 40px);
        position: relative;

        .j-loding {
            height: calc(100% - 40px);
            box-sizing: border-box;

            :deep(.j-loding) {
                height: 100%;
            }
        }

        .j-auto {
            height: calc(100% - 40px);
            overflow: auto;
            box-sizing: border-box;
        }

        .j-none {
            height: calc(100% - 85px);
            overflow: auto;
            box-sizing: border-box;
        }

    }

    .col_title {
        text-align: left;
        color: #b1b6c6;
        line-height: 17px;

        .icon {
            font-size: 15px;
        }
    }

    .image {
        width: 20px;
        height: 20px;
    }

    .col_1 {
        // width: 51px;
        font-family:
            PingFangSC-Regular,
            PingFang SC;
        // line-height: 20px;
        // padding-left: 20px;
        overflow: hidden;
        display: flex;

        .long-text {
            flex: 1;
            display: block;
            text-overflow: ellipsis;
            text-wrap: nowrap;
            overflow: hidden;
        }
    }

    .col_2 {
        justify-content: flex-end;
        text-align: right;
    }

    .col_3 {
        font-family:
            PingFangSC-Regular,
            PingFang SC;
        flex-grow: 1.5 !important;
        justify-content: flex-end;

        .c-left {
            flex: 0.6;
            display: inline-block;
            text-align: right;
        }

        .c-right {
            flex: 0.4;
            display: inline-block;
            text-align: left;
            margin-left: 10px;
        }
    }

    .col_4 {
        flex-grow: 1.5;
        // text-align: right;
        justify-content: flex-end;
        padding-right: 20px;
        display: flex;
        align-items: center;
        // flex-grow: 1 !important;
        // gap: 10px;

        .c-left {
            // flex: 1 0 0;
            flex: 0.6;
            // width: 70%;
            display: inline-block;
            // width: 0;
            text-align: right;
        }

        .c-right {
            display: flex;
            flex: 0.4;
            display: inline-block;
            // justify-content: flex-start;
            // width: 30%;
            // display: inline-block;
            // text-align: left;
        }
    }

    .v-row {
        border-bottom: 1px solid #2d3338;
        margin: 0 !important;
        height: 38px;
        flex-wrap: nowrap;

        &:last-child {
            border: none !important;
        }
    }

    :deep(.i-navs) {
        margin-top: 0;
    }
}


.col-first {
    padding-inline-start: 20px;
}







.row-first {
    border-bottom: 1px solid #2d3338;
    background-color: var(--card);
    height: 38px;
    z-index: 1;
    margin: 0 !important;

    .v-col {
        .s-warp {
            padding-left: 5px;
        }
    }
}

.v-container {
    padding: 0 !important;
    max-width: 100% !important;
}

.money {
    display: flex;

    .left-m {
        flex: 0.7;
        width: 0;
        text-align: right;
    }

    .right-m {
        flex: 0.3;
        width: 0;
        text-align: left;
        margin-left: 12px;
        font-size: 10px;
    }
}

.center {
    text-align: center !important;
    flex-grow: 2 !important;
}

.money {
    flex-grow: 2 !important;
}

.coin-t {
    width: 20px;
    height: 20px;
    background: #b3b3b3;
    border-radius: 50%;
    overflow: hidden;
    object-fit: contain;
}

.sps-col {
    display: flex;
    align-items: center;
    // gap: 12px;
}

.col-gap {
    gap: 12px;
}

.pagination-top {
    margin-top: 10px;
}
</style>
